package com.aceitunaproject.server.settlement;

import java.util.logging.Logger;

import com.aceitunaproject.server.AceitunaContext;
import com.aceitunaproject.server.counter.Counter;
import com.aceitunaproject.server.entity.settlement.Settlement;
import com.aceitunaproject.server.entity.unit.Unit;
import com.aceitunaproject.server.map.MapTile;
import com.aceitunaproject.shared.exceptions.gamerules.EnumIllegalAction;
import com.aceitunaproject.shared.exceptions.gamerules.IllegalActionException;
import com.sun.sgs.app.AppContext;

/**
 * Settlement Manager interface implementation
 * 
 * @author Federico Bergstein
 * 
 * 
 */
public class SettlementManagerImpl implements SettlementManager {

	private static final String SETTLEMENT_PREFIX = "SETTLEMENT";
	private static final String COUNTERNAME = "SettlementCounter";

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.aceitunaproject.server.settlement.SettlementManager#buildSettlement
	 * (java.lang.String, int, int, int,
	 * com.aceitunaproject.server.player.Player,
	 * com.aceitunaproject.server.player.Player, double,
	 * com.aceitunaproject.server.entity.EntityRelationships)
	 */
	@Override
	public Settlement buildSettlement(String name, int positionX,
			int positionY, Unit unit) throws IllegalActionException {

		MapTile tile = AceitunaContext.getMapManager().getTile(positionX,
				positionY);

		if (tile.getSettlement() != null) {
			throw new IllegalActionException(
					EnumIllegalAction.BUILD_SETTLEMENT_SETTLEMENT_ALREADY_EXISTS_IN_TILE);
		}

		Settlement newSettlement = createSettlement(name, unit);
		Logger.getLogger(this.getClass().getName()).info(
				"placing settlement " + name + " in " + positionX + " , "
						+ positionY);

		tile.placeSettlement(newSettlement);

		return newSettlement;
	}

	private Settlement createSettlement(String name, Unit unit) {
		Settlement newSettlement = new Settlement(getNewCount(), name, unit
				.getOwner(), unit.getController(), unit);

		AppContext.getDataManager().setBinding(
				SETTLEMENT_PREFIX + newSettlement.getId(), newSettlement);

		Logger.getLogger(this.getClass().getName()).info(
				"building settlement " + name + " in "
						+ unit.getCurrentPosition().x + " , "
						+ unit.getCurrentPosition().y);

		return newSettlement;
	}

	private static Long getNewCount() {
		if (!Counter.counterExists(COUNTERNAME)) {
			Counter.createCounter(COUNTERNAME);
		}
		return Counter.getNewCount(COUNTERNAME);
	}

	@Override
	public Settlement getSettlement(long settlementID) {
		Settlement theSettlement = null;

		theSettlement = (Settlement) AppContext.getDataManager().getBinding(
				SETTLEMENT_PREFIX + settlementID);

		return theSettlement;

	}

}
